<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="施肥管理"></page-header>

        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的肥料内容"
                v-model="searchKeyword"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>

        <filter-tabs :activeTab="activeTab" @tab-change="handleFilterChange" />

        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredFertilizerList"
                :key="index"
                :item="item"
                @clickItem="viewDetail(item)"
                @edit="editFertilizerRecord(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <view style="display: flex; align-items: center">
                            <image
                                class="icon-wrapper"
                                style="margin-right: 10rpx"
                                src="/static/images/shifei.png"
                                mode="aspectFill"></image>
                            <view class="date-title">
                                {{ getFertilizerCategoryLabel(item.fertilizerCategory) }}
                            </view>
                            <view class="header-tag" style="margin-left: 10rpx">
                                <text>
                                    {{
                                        getFertilizerTypeLabel(
                                            item.fertilizerCategory,
                                            item.fertilizerTypeName
                                        )
                                    }}
                                </text>
                            </view>
                        </view>
                        <text class="date-small">
                            {{ formatDate(item.startDate || item.createTime) }}
                        </text>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <div class="space-between">
                            <view class="info-row">
                                <text class="info-label text-nowrap">施肥地块</text>
                                <text class="info-value text-nowrap">
                                    {{ item.plotName }}-{{ item.fieldName }}
                                </text>
                                <text class="info-value text-nowrap">
                                    {{
                                        getFertilizationMethodLabel(item.applicationMethod) ||
                                        '未指定'
                                    }}
                                </text>
                            </view>

                            <view class="info-row">
                                <text class="info-label text-nowrap">负责人</text>
                                <text class="info-value text-nowrap">
                                    {{ item.personInCharge || '未指定' }}
                                </text>
                            </view>
                        </div>

                        <div class="space-between">
                            <view class="info-row">
                                <text class="info-label text-nowrap">用量</text>
                                <text class="info-value text-nowrap">
                                    {{ item.dosage || 0 }} kg
                                </text>
                            </view>
                            <view class="info-row">
                                <text class="info-label text-nowrap">肥料名称</text>
                                <text class="info-value text-nowrap">
                                    {{ item.fertilizerName || '未指定' }}
                                </text>
                            </view>

                            <view class="info-row">
                                <text class="info-label text-nowrap">面积</text>
                                <text class="info-value text-nowrap">{{ item.area || 0 }} 亩</text>
                            </view>
                            <view class="info-row">
                                <text class="info-label text-nowrap">亩均</text>
                                <text class="info-value text-nowrap">
                                    {{ calculateAveragePerMu(item) }} kg/亩
                                </text>
                            </view>
                        </div>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>

                        <view class="item-images" v-if="item.images">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredFertilizerList.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 无数据提示 -->
        <empty-data v-if="filteredFertilizerList.length === 0 && !loading" />

        <view
            class="add-button"
            @click="navigateTo('/pages/agriculture/fertilizerManagement/addFertilizer')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { fertilizer } from '@/utils/api/index.js'
// 导入格式化函数
import { formatDateChinese, formatImages } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            title: '施肥管理',
            activeTab: 'all',
            searchKeyword: '',
            fertilizerList: [],
            loading: false,
            loadingMore: false, // 加载更多状态
            hasMore: true, // 是否还有更多数据
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
        }),
        filteredFertilizerList() {
            return this.fertilizerList
        },
    },
    onLoad() {
        // 确保字典数据已加载
        this.loadDictData()
    },
    onShow() {
        this.fetchFertilizerList()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchFertilizerList()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        // 计算亩均用量
        calculateAveragePerMu(item) {
            if (!item.area || !item.dosage) return 0
            const average = (item.dosage / item.area).toFixed(2)
            return parseFloat(average)
        },

        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                // 加载施肥类型字典
                await this.getDictByType('fertilization_type')

                // 加载施肥方式字典
                await this.getDictByType('fertilization_method')

                // 加载肥料类型字典
                await this.getDictByType('fertilizer_type')

                // 预加载各种施肥类型的肥料字典
                const fertilizerTypes = this.getDictByType('fertilization_type')
                for (const type of fertilizerTypes) {
                    if (type.value) {
                        await this.getDictByType(type.value)
                    }
                }
            } catch (error) {
                console.error('加载字典数据失败:', error)
            }
        },

        // 获取施肥类型的显示文本
        getFertilizerCategoryLabel(value) {
            if (!value) return '未指定'
            return this.getDictLabel('fertilization_type', value) || value
        },

        // 获取肥料类型的显示文本
        getFertilizerTypeLabel(category, value) {
            if (!value) return '未指定'
            if (category) {
                return this.getDictLabel(category, value) || value
            }
            return value
        },

        // 获取施肥方式的显示文本
        getFertilizationMethodLabel(value) {
            if (!value) return '未指定'
            return this.getDictLabel('fertilization_method', value) || value
        },

        // 处理筛选变化
        handleFilterChange(tabValue, filterData) {
            this.activeTab = tabValue

            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的日期和地块筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.plotId

            // 添加新的筛选条件
            if (filterData) {
                if (filterData.startDate && filterData.endDate) {
                    this.pageParams.startDate = filterData.startDate
                    this.pageParams.endDate = filterData.endDate
                }

                if (filterData.areaId) {
                    this.pageParams.plotId = filterData.areaId
                }
            }

            // 重新请求接口
            this.fetchFertilizerList()
        },

        // 处理搜索变化
        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKeyword) {
                this.pageParams.fertilizerName = this.searchKeyword
            } else {
                delete this.pageParams.fertilizerName
            }

            // 重新请求接口
            this.fetchFertilizerList()
        },

        async fetchFertilizerList(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await fertilizer.getFertilizerPage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.fertilizerList = [...this.fertilizerList, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.fertilizerList = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                } else {
                    // 如果API请求失败，使用默认数据
                    if (!isLoadMore) {
                        this.fertilizerList = this.getDefaultData()
                    }
                }
            } catch (error) {
                console.error('获取施肥记录失败:', error)
                uni.showToast({
                    title: '获取数据失败',
                    icon: 'none',
                })
                // 使用默认数据
                if (!isLoadMore) {
                    this.fertilizerList = this.getDefaultData()
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 获取默认数据，在API请求失败时使用
        getDefaultData() {
            return [
                {
                    id: 1,
                    fertilizerCategory: 'base_fertilizer',
                    fertilizerTypeName: '0',
                    plotId: '1',
                    fieldId: '2',
                    plotName: '1号地块',
                    fieldName: '2号条田',
                    dosage: 20,
                    concentration: 5,
                    applicationMethod: '0',
                    startDate: '2023-07-23 09:30',
                    personInCharge: '王记得',
                    images: '/static/images/fertilizer/fertilizer1.jpg',
                },
                {
                    id: 2,
                    fertilizerCategory: 'seed_fertilizer',
                    fertilizerTypeName: '1',
                    plotId: '1',
                    fieldId: '2',
                    plotName: '1号地块',
                    fieldName: '2号条田',
                    dosage: 20,
                    concentration: 5,
                    applicationMethod: '1',
                    startDate: '2023-07-23 14:15',
                    personInCharge: '王记得',
                    images: '/static/images/fertilizer/fertilizer2.jpg',
                },
                {
                    id: 3,
                    fertilizerCategory: 'topdressing',
                    fertilizerTypeName: '2',
                    plotId: '1',
                    fieldId: '2',
                    plotName: '1号地块',
                    fieldName: '2号条田',
                    dosage: 20,
                    concentration: 5,
                    applicationMethod: '2',
                    startDate: '2023-07-23 16:45',
                    personInCharge: '王记得',
                    images: '/static/images/fertilizer/fertilizer3.jpg',
                },
            ]
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.fetchFertilizerList(true)
        },

        navigateTo(url) {
            uni.navigateTo({
                url,
            })
        },

        formatDate(dateString) {
            return formatDateChinese(dateString)
        },

        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        viewDetail(item) {
            // 跳转到详情页面
            uni.navigateTo({
                url: `/pages/agriculture/fertilizerManagement/addFertilizer?id=${item.id}`,
            })
        },

        editFertilizerRecord(item) {
            // 编辑记录，跳转到编辑页面
            uni.navigateTo({
                url: `/pages/agriculture/fertilizerManagement/addFertilizer?id=${item.id}`,
            })
        },

        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条施肥记录吗？`,
                success: (res) => {
                    if (res.confirm) {
                        this.deleteFertilizerRecord(item.id)
                    }
                },
            })
        },

        async deleteFertilizerRecord(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await fertilizer.deleteFertilizerRecord(id)

                if (res.code === 0 && res.data) {
                    // 删除成功，更新列表
                    const index = this.fertilizerList.findIndex((item) => item.id === id)
                    if (index !== -1) {
                        this.fertilizerList.splice(index, 1)
                    }

                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除施肥记录失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },
    },
}
</script>

<style lang="scss">
.header-tag {
    width: 88rpx;
    height: 44rpx;
    background: #e6ffe5;
    border-radius: 4rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    font-family: OPPOSans, OPPOSans;
    font-weight: 400;
    font-size: 24rpx;
    color: #1cb356;
}
</style>
